package com.itcam.tomcat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @author : Cammy.Wu
 * Description : 
 */

@WebServlet("/request")
public class RequestServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("post请求");
        this.doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("get请求");
        // 获取请求行数据
        // 获取请求中的请求方式
        String method = req.getMethod();
        System.out.println("method = " + method);
        // 获取请求中的完整地址
        StringBuffer requestURL = req.getRequestURL();
        System.out.println("requestURL = " + requestURL);
        // 获取请求中的资源路径
        String requestURI = req.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        // 获取请求中的协议
        String scheme = req.getScheme();
        System.out.println("scheme = " + scheme);

        // 获取请求头数据
        // 根据key获取value的值
        String userAgent = req.getHeader("User-Agent");
        System.out.println("userAgent = " + userAgent);
        System.out.println("----------------------------");
        // 获取请求头信息中所有key的枚举对象
        Enumeration<String> headerNames = req.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = req.getHeader(key);
            System.out.println(key + " = " + value);
        }

        // 获取用户请求数据
        // 无论请求方式是post还是get，获取用户数据的方式不变
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println(username + " = " + password);
        System.out.println("----------------------------");
        // 获取用户数据中的所有key的枚举对象
        Enumeration<String> parameterNames = req.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = req.getParameter(key);
            System.out.println(key + " = " + value);
        }
        // 获取相同key的多个数据值，例如checkbox
        String[] parameterValues = req.getParameterValues("fav");
        for (String parameterValue : parameterValues) {
            System.out.println(parameterValue);
        }

        // 其他常用方法
        // 获取远程客户端的主机地址
        String remoteAddr = req.getRemoteAddr();
        // 获取远程客户端的主机名称
        String remoteHost = req.getRemoteHost();
        // 获取远程客户端的端口号
        int remotePort = req.getRemotePort();
        System.out.println(remoteAddr + " : " + remoteHost + " : " + remotePort);
    }

}
